import RNFS from 'react-native-fs';
import {Dirs, FileSystem} from 'react-native-file-access';
import dayjs from 'dayjs';
import {fileTypeFromFile} from 'file-type';
import RNFileType from 'react-native-file-type';
import sortArray from 'sort-array';
import {round} from 'lodash';
import getDirSize from '@/fun/getDirSize';

const getFileInfo = async item => {
  const fPath = item.path;
  const dirArr = fPath.split('/');
  dirArr.pop();
  const pPath = dirArr.join('/');

  // const dirInfo = getDirSize
  const rtItem = {
    v: dayjs().valueOf(),
    pPath,
    path: item.path,
    type: item.type,
    size: item.size,
  };
  if (item.type === 'directory') {
    const dirInfo = await getDirSize({targetPath: item.path});
    rtItem.size = dirInfo.size;
    rtItem.sKB = dirInfo.sizeKB;
    rtItem.sMB = dirInfo.sizeMB;
    rtItem.sGB = dirInfo.sizeGB;
    rtItem.total = dirInfo.total;
    rtItem.tsr = dirInfo.totalSonDir;
    rtItem.tsf = dirInfo.totalSonFile;
  }
  return rtItem;
};
export default async ({targetPath = ''}) => {
  let total = 0;
  let size = 0;

  const rtList = [];
  const refuseNames = ['android', 'libs', 'log', 'null'];
  return new Promise(async (resolve, reject) => {
    const lastDirPath = 'last-dir-' + dayjs().format('YYYYMMDDHHmmssSSS');
    let oneAllFiles = await FileSystem.statDir(targetPath);
    oneAllFiles.push({
      path: lastDirPath,
      type: 'directory',
      filename: '',
    });

    // oneAllFiles = oneAllFiles
    // const oneSonDirs = oneAllFiles.filter(item => item.type === 'directory');

    const addRtList = async (list = []) => {
      for (let i = 0; i < list.length; i++) {
        const item = list[i];
        const newItem = await getFileInfo(item);
        if (item.path !== lastDirPath) {
          rtList.push(newItem);
        }
      }
    };

    const ckUserDir = item =>
      item.type === 'directory' &&
      !item.filename.startsWith('.') &&
      !refuseNames.includes(item.filename.toLocaleLowerCase());
    const oneSonDirs = oneAllFiles.filter(ckUserDir);
    const oneSonFiles = oneAllFiles.filter(item => item.type !== 'directory');

    await addRtList(oneSonDirs);
    await addRtList(oneSonFiles);

    const fun = async ({list = []}) => {
      for (const nowItem of new Set(list)) {
        if (nowItem.path === lastDirPath) {
          resolve(rtList);
        } else {
          const allFiles = await FileSystem.statDir(nowItem.path);
          // const sonDirs = allFiles.filter(item => item.type === 'directory');
          const sonDirs = allFiles.filter(ckUserDir);
          const sonFiles = allFiles.filter(item => item.type !== 'directory');

          await addRtList(sonDirs);
          await addRtList(sonFiles);

          if (sonDirs.length > 0) {
            await fun({list: sonDirs});
          }
        }
      }
    };
    fun({list: oneSonDirs});
  });
};
